package com.cyzy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cyzy.dao.Goods;
import com.cyzy.dao.OrderDto;
import com.cyzy.mapper.*;
import com.cyzy.pojo.*;
import com.cyzy.service.OrderItemsService;
import com.cyzy.service.OrderService;
import com.cyzy.vo.ArtGoodVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @author cuncun
 * @create 2025-06-18 上午11:25
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders> implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private DistributionRecordMapper distributionRecordMapper;

    @Autowired
    private CourseParentsMapper courseParentsMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private OrderItemsMapper orderItemsMapper;


    @Override
    public List<OrderDto> selectOrder(String type, Integer id) {
        List<OrderDto> orderDtos = orderMapper.selectOrder(type, id);
        //计算购买商品数量
        for (OrderDto orderDto : orderDtos) {
            orderDto.setNumber(orderDto.getGoods().size());
        }
        return orderDtos;
    }

    @Override
    public int deleteOrder(String orderNo) {
        //修改订单状态为删除
        LambdaUpdateWrapper<Orders> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(Orders::getOrderNo,orderNo)
                .set(Orders::getIsDeleted,1);
        int update = orderMapper.update(wrapper);
        System.out.println(update + " ----orderMapper.update(wrapper)");
        return orderMapper.update(wrapper);
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public String submitOrders(ArtGoodVo artGoodVo) {
        Orders orders = new Orders();
        //判断分销员是否存在
        if(artGoodVo.getDistributionId()!= null){
            LambdaQueryWrapper<DistributionRecord> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(DistributionRecord::getDistributorId,artGoodVo.getDistributionId());
            DistributionRecord distributionRecord = distributionRecordMapper.selectOne(wrapper);
//            分销员不存在订单就流掉
           if(distributionRecord == null){
               return "分销员不存在";
           }
        }
        //查询购买者信息
        //如果是家长就去查家长信息
        if(artGoodVo.getRole().equals("parent")){
            LambdaQueryWrapper<CourseParent> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(CourseParent::getParentId,artGoodVo.getStoreId());
            CourseParent courseParent = courseParentsMapper.selectOne(wrapper);
            orders.setUserId(courseParent.getParentId());
            orders.setUserName(courseParent.getParentName());
            orders.setUserPhone(courseParent.getParentPh());
        }
        //如果是老师就去查老师信息
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUserId,artGoodVo.getStoreId());
        User user = userMapper.selectOne(wrapper);
        orders.setUserId(user.getUserId());
        orders.setUserName(user.getUserName());
        orders.setUserPhone(user.getPhonenumber());

        //统一处理别的数据
        String orderNo =  generateRamId();
        orders.setOrderNo(orderNo);//订单编号
        orders.setCampusId(artGoodVo.getCampusId());
        orders.setTotalAmount(artGoodVo.getTotalAmount());
        orders.setPayAmount(artGoodVo.getTotalAmount());
        orders.setReceiverName(artGoodVo.getReceiverName());
        orders.setReceiverPhone(String.valueOf(artGoodVo.getReceiverPhone()));
        orders.setReceiverName(artGoodVo.getReceiverName());
        orders.setReceiverAddress(artGoodVo.getReceiverAddress());
        orders.setRole(artGoodVo.getRole());
        orders.setPayStatus(0);
        // 获取当前时间并格式化为字符串
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedNow = LocalDateTime.now().format(formatter);
        orders.setCreatedTime(formattedNow);
        orders.setUpdatedTime(formattedNow);

        //插入订单
        int insert = orderMapper.insert(orders);
        //查询订单编号
        LambdaQueryWrapper<Orders> wrappers = new LambdaQueryWrapper<>();
        wrappers.eq(Orders::getOrderNo,orderNo);
        Orders orders1 = orderMapper.selectOne(wrappers);
        List<OrderItems> os = new ArrayList<>();
        if(insert == 1){
            //去给orderItems表插入
            for (ArtGood artGood : artGoodVo.getCartList()) {
                //给商品赋值
                OrderItems orderItems = new OrderItems();
                orderItems.setOrderId(orders1.getOrderId());
                orderItems.setGoodId(artGood.getGoodId());
                orderItems.setCampusId(orders.getCampusId());
                orderItems.setGoodOriginalPrice(artGood.getGoodOriginalPrice());
                orderItems.setGoodDiscountPrice(artGood.getGoodDiscountPrice());
                orderItems.setQuantity(artGood.getQuantity());
                orderItems.setPayStatus(0);
                orderItems.setOrderItemStatus(0);
                orderItems.setCreatedTime(formattedNow);
                orderItems.setUpdatedTime(formattedNow);
                os.add(orderItems);
            }
            orderItemsMapper.insertBatch(os);
        }
        return "sss";
    }

    @Override
    public String payOrder(OrderDto OrderDto) {

        //查出该订单的信息，以便获取分销员
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Orders::getOrderNo,OrderDto.getOrderNo());
        Orders orders = orderMapper.selectOne(wrapper);
        //将order表中支付状态改为已支付
        LambdaUpdateWrapper<Orders> wrappers = new LambdaUpdateWrapper<>();
        wrappers.eq(Orders::getOrderNo,OrderDto.getOrderNo())
                .set(Orders::getPayStatus,1);
        int update = orderMapper.update(wrappers);
        if(update == 1 ){
            return "修改订单成功！";
        }
        return "修改订单失败！";
    }

    public static String generateRamId() {
        return "ORD" + System.currentTimeMillis() + UUID.randomUUID().toString().substring(0, 8);
    }
}
